package com.xywy.common.sync;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.google.gson.Gson;
import com.xywy.common.bean.WeightDataFormServer;
import com.xywy.common.util.MD5Util;
import com.xywy.fwc.net.BaseParser;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.StringParser;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.dao.WeightDataDao.Properties;
import com.xywy.wjk.observer.ObserverConstants;
import com.xywy.wjk.util.WjkConstant;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * 体重数据同步方法；
 * 
 * @author yangyu
 * 
 */
public class SyncWeightScaleData implements ISyncBleDevice {

	private Context mContext;
	private WeightDataDao weightDataDao; // 体重数据操作
	private SharedPreferences sp;
	private Editor editor;
	private String userid = "";
	public static final String deleteUrl = "http://api.yun.xywy.com/index.php/api/setdata/del_data/";

	private User current_user;
	
	public SyncWeightScaleData(Context context, WeightDataDao weightDataDao) {
		this.mContext = context;
		this.weightDataDao = weightDataDao;
		sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		editor = sp.edit();
		current_user = UserKeeper.getCurrentUser(mContext);
//		userid = sp.getString("userid", "");
		userid = current_user.getUserid();
	}

	@Override
	public List getUnuploadData() {
		long lastSaveTime = sp.getLong("last_download_weight_time", 1000); // 最后的上传时间
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Id);
		qb.where(Properties.Date.gt(lastSaveTime));
		return qb.list();
	}

	@Override
	public void syncDataFormServer() {
		long lastDownLoadTime = sp.getLong(userid+"last_download_weight_time", 1000); // 最后的下载时间；
		String device_id = "temp_automactily_device_identify";
		String appCount = "xywy_tizhong";
		String dataType = "tizhong";
		String time = (lastDownLoadTime / 1000) + "";
		String maxItem = "200";
		String curPage = "1";
		String sn = "";
		try {
			sn = MD5Util.md5(SECRETKEY_WEIGHT_SCALEF + device_id + dataType
					+ userid + time + maxItem + curPage + appCount);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String urlStr = "http://api.yun.xywy.com/index.php/api/getdata/data/"
				+ device_id + "/" + appCount + "/" + dataType + "/" + userid
				+ "/" + time + "/" + maxItem + "/" + curPage + "/" + sn + "/";

		Request.requestData(new BaseParser<List<WeightDataFormServer>>() {

			@Override
			public List<WeightDataFormServer> parseJson(String result) {
				List<WeightDataFormServer> datas = null;
//				Log.d(TAG, "体重 ：从服务器获取体重数据需要更新的解析: ");
				Log.e("syncweightscaledata---", result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					int status = jsonObject.getInt("status");
					if (status == 0) { // 正确与服务器交互；
//						Log.d(TAG, "体重 ：从服务器获的状态为  0  ");
						String data = jsonObject.getString("title");
						datas = new ArrayList<WeightDataFormServer>();
						
						JSONArray jsonArray = jsonObject.optJSONArray("data");
						for(int i= 0;i<jsonArray.length();i++){
							WeightDataFormServer wf = new WeightDataFormServer();
							JSONObject item = (JSONObject) jsonArray.get(i);
							wf.setDatatime(Double.parseDouble(item.optString("datatime")));
							wf.setXywy_userid(item.optString("xywy_userid"));
							wf.setApp_user_id(item.optString("app_user_id"));
							wf.setWeight(Float.parseFloat(item.optString("weight")));
							wf.setBmidata(Float.parseFloat(item.optString("bmidata")));
							wf.setFat(Float.parseFloat(item.optString("fat")));
							wf.setWater(Float.parseFloat(item.optString("water")));
							wf.setMuscle(Float.parseFloat(item.optString("muscle")));
							wf.setBone(Float.parseFloat(item.optString("bone")));
							wf.setBmrh(Float.parseFloat(item.optString("bmrh")));
							wf.setSfat(Float.parseFloat(item.optString("sfat")));
							wf.setInfat(Float.parseFloat(item.optString("infat")));
							wf.setBodyage(Float.parseFloat(item.optString("bodyage")));
							wf.setApp_data(item.optString("app_dat"));
							wf.setShou_data(item.optString("shou_data"));
							datas.add(wf);
						}
						return datas;
					}else {
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
					return null;
				}

			}
		}, new DataCallBack<List<WeightDataFormServer>>() {

			@Override
			public void dataCall(List<WeightDataFormServer> lists) {
				if (lists == null) {
					Log.d(TAG, "体重：当前数据获取失败，或者解析异常， 导致同步数据库失败！");
					return;
				}else if (lists.size() == 0) {
					Log.d(TAG, "体重：没有一条数据");
					uploadDataToServer(getUnuploadData());
					return;
				}
				
//				uploadDataInRAM(getUnuploadData());
//				Log.d(TAG, " 体重：未同步的数据已经成功插入");
				editor.putBoolean("isBind", true).commit();
				for (WeightDataFormServer list : lists) {
					long date = (long) (list.getDatatime() * 1000); // *1000
																	// 因为服务器上为ios
					if(!dataCanInsert(date)){
						continue;
					}
					WeightData data = new WeightData(null, list.getWeight(),
							list.getFat(), list.getWater(), list.getMuscle(),
							list.getBone(), list.getBmrh(), list.getSfat(),
							list.getInfat(), list.getBodyage(),userid, null,
							"temp_automactily_device_identify",
							"temp_handly_device_identify", date);
					
					
//					Log.e("现在开始插入------", data.getDate()+"");
					
					
					
					weightDataDao.insert(data);
				}
				Intent intent = new Intent(WjkConstant.GET_DATA);
				mContext.sendBroadcast(intent);
				// 将数据保存之后，获取最后一条的时间来替换本地数据；
				editor.putLong(
						userid+"last_download_weight_time",
						(long) (lists.get(lists.size() - 1).getDatatime() * 1000))
						.commit();
//				uploadDataToServer(getUnuploadData());
				//这个时候  要通知weightfragment 叫他来更新这个代码

				// 3 当数据正常处理之后 ， 开始上传1中获取到的数据；

			}

		}, urlStr);

	}
	
	/**
	 * 为了避免重复插入 也就是数据库中  大于time 1s 和 小于1s 之间的如果没有重复的 那么插入
	 * 
	 * @param time
	 * @return
	 */
	public boolean dataCanInsert(long time){
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.where(Properties.Date.gt(time-1000));
		qb.where(Properties.Date.gt(time+1000));
		List<WeightData> list = qb.list();
		if(list != null && list.size()>0)
		   return false;
		return true;
	}

	@Override
	public void uploadDataInRAM(List baseDatas) {

		final List<WeightData> datas = baseDatas;
		if (datas == null || datas.size() < 1) {
			Log.d(TAG, "没有从数据库中获取到数据，不需要执行上传方法 。节省流量");
			sp.edit()
			.putLong("last_download_weight_time",
					System.currentTimeMillis())
			.commit();
			return;
		}
		/* 循环更改当前的time时间 ，避免上传中之后与ios数据不统一 */
		List<WeightData> list = new ArrayList<WeightData>();
		for (WeightData data : datas) {
			long date = data.getDate();
			WeightData dataTemp = data.clone();
			dataTemp.setDate(date / 1000);
			list.add(dataTemp);
		}

		HashMap<Object, Object> params = new HashMap<Object, Object>();
		params.put("app_username", "xywy_tizhong");
		String userid = sp.getString("userid", "");
		params.put("xywy_userid", userid);
		params.put("sort", "tizhong");
		// -------------------
		String dataStr = turn2ServerJsonData(list, userid);
		params.put("data", dataStr);
		// -------------------
		String sn = SECRETKEY_WEIGHT_SCALEF + userid + "tizhong" + dataStr
				+ "xywy_tizhong";

		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Log.d(TAG, "同步体重数据，现在开始");
		Request.postData(new BaseParser() {

			@Override
			public Object parseJson(String result) {
				try {
					Log.d(TAG, "同步体重数据，以下为结果");
					JSONObject jsonObject = new JSONObject(result);
					int status = jsonObject.getInt("status");
					if (status == 0) {
						Log.d(TAG, "体重上传成功");
						sp.edit()
								.putLong("last_download_weight_time",
										datas.get(datas.size() - 1).getDate())
								.commit();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				return null;
			}

		}, new DataCallBack<String>() {

			@Override
			public void dataCall(String str) {

			}
		}, "http://api.yun.xywy.com/index.php/api/setdata/data_all/", params);

	}

	String sort = "tizhong";

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(List<WeightData> datas, String userID) {
		Gson gson = new Gson();
		List<WeightDataFormServer> jsons = new ArrayList<WeightDataFormServer>();
		for (WeightData data : datas) {
			WeightDataFormServer dataFormServer = new WeightDataFormServer();
			dataFormServer.setApp_data(data.getDevice_id());
			dataFormServer.setApp_user_id("");
			int height = sp.getInt("height", -1);
			int bmi = (int) (Math
					.round((data.getWeight() / ((height / 100) * (height / 100))) * 10)) / 10;
			dataFormServer.setBmidata(bmi);
			dataFormServer.setBmrh(data.getMetabolisim());
			dataFormServer.setBodyage(data.getBodyAge());
			dataFormServer.setBone(data.getBoneData());
			dataFormServer.setDatatime(data.getDate()/1000);
			dataFormServer.setFat(data.getFatData());
			dataFormServer.setInfat(data.getFatInBody());
			dataFormServer.setMuscle(data.getMuscleData());
			dataFormServer.setSfat(data.getFatUnderSkin());
			dataFormServer.setShou_data(data.getHand_str());
			dataFormServer.setWater(data.getWaterData());
			dataFormServer.setWeight(data.getWeight());
			dataFormServer.setXywy_userid(userID);
			dataFormServer.setApp_username("xywy_tizhong");
			dataFormServer.setSort(sort);
			jsons.add(dataFormServer);
		}

		return gson.toJson(jsons);
	}
	/**
	 * 删除体重数据
	 * @param data
	 */
    public void syncDeleteWeightData(WeightData data){
    	HashMap<Object, Object> params = new HashMap<Object, Object>();
		params.put("app_username", "xywy_tizhong");
		String userid = sp.getString("userid", "");
		params.put("xywy_userid", userid);
		params.put("sort", "tizhong");
		long dataTime =  data.getDate()/1000 ;
		params.put("datatime", data.getDate()/1000);
		String sn = SECRETKEY_WEIGHT_SCALEF + userid + "tizhong" + dataTime
				+ "xywy_tizhong";
		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	   Request.postData(new StringParser(), delete_call, deleteUrl, params);
    }
    
    DataCallBack<String> delete_call = new DataCallBack<String>() {
		
		@Override
		public void dataCall(String result) {
			// TODO Auto-generated method stub
			System.out.println("delete---"+result);
		}
	};
	
	
	/**
	 * 将数据上传到服务器
	 * 
	 * @param data
	 */
	private String secret_key = "213aBc$l;@13";
//	private String sort = "tizhong";

	private void uploadDataToServer(final List<WeightData> datas) {
//		data.setDate(data.getDate() / 1000);
		HashMap<Object, Object> params = new HashMap<Object, Object>();
		params.put("app_username", "xywy_tizhong");
//		String userid = sp.getString("userid", "");
		params.put("xywy_userid", userid);
		params.put("sort", sort);
		String dataStr = turn2ServerJsonData(datas, userid);
		Log.e("体重上传数据值", dataStr);
		params.put("data", dataStr);
		String sn = secret_key + userid + sort + dataStr + "xywy_tizhong";
		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Request.postData(new MyPaser(datas), new DataCallBack<String>() {

			@Override
			public void dataCall(String str) {
				try {
					JSONObject json = new JSONObject(str);
					int status = json.optInt("status");
					if(status ==0){
						sp.edit()
						.putLong("last_download_weight_time",
								datas.get(0).getDate())
						.commit();
					}else {
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("上传本次体重的返回值" + str);
			}
		}, "http://api.yun.xywy.com/index.php/api/setdata/data_all/", params);

	}
	
	class MyPaser extends BaseParser<String> {

		List<WeightData> datas ;

		MyPaser(List<WeightData> datas ) {
			this.datas = datas;
		}

		@Override
		public String parseJson(String result) {
			try {
				JSONObject jsonObject = new JSONObject(result);
				int status = jsonObject.getInt("status");
				if (status == 1) {
					if(datas!= null && datas.size()>0)
					sp.edit().putLong("last_download_weight_time", datas.get(0).getDate()).commit();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}
	}

}
